<?php 
namespace common\models\info;

use common\component\BaseActiveRecord;
use common\component\Constant;
use common\utils\CommonUtil;
use yii\behaviors\TimestampBehavior;
use yii\db\Query;
use yii\helpers\Url;

/**
 * This is the model class for table "{{%zt_tags_relation}}".
 *
 * @property int $object_id 文章id
 * @property int $tag_id 标签id
 * @property int $created_at 加入时间
 */
class TagsRelation extends BaseActiveRecord
{

    const TYPE_ARTICLE = 1;  //文章
    const TYPE_USER = 2;     //用户

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%zt_tags_relation}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['object_id', 'tag_id','created_at'], 'integer'],
            [['object_id', 'tag_id'], 'unique', 'targetAttribute' => ['object_id', 'tag_id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'object_id' => 'Object ID',
            'tag_id' => 'Tag ID',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at']
                ]
            ]
        ];
    }

    public function afterDelete()
    {
        parent::afterDelete();
        Tags::fieldIncrAndReduc($this->tag_id,Tags::TOTAL_ARTICLE,Tags::REDUCE);
    }


    public function afterFind()
    {
        parent::afterFind();
        $this->ui();
    }

    public function ui() {
        $title = Article::getFieldById($this->object_id,"title");
        $this->ui["object_name"] = $title;
        $this->ui["tag_name"] = Tags::getFieldById($this->tag_id,"tag_name");
    }

    /**
     * 获取对像id对应的标签ID
     * @param $objId
     * @param int $type
     * @return array
     */
    public static function arrTagIdsList($objId) {
        $data = static::find()->select("tag_id")->where(['object_id'=>$objId])->asArray()->column();
        return $data;
    }

    /**
     * 添加标签
     * @param $objId
     * @param $tags
     * @param int $type
     */
    public static function addTags($objId,$tags) {
        if (!count($tags)) return;
        foreach ($tags as $tag) {
            $model = new self();
            $model->object_id = $objId;
            $model->tag_id = $tag;
            if (!$model->save()) {
                \Yii::error("添加标签关系对应失败，原因:".$model->getErrorsToString());
            }
        }
        return;
    }

    /**
     * 删除标签
     * @param $objId
     * @param $tags
     * @param int $type
     */
    public static function reduceTags($objId,$tags) {
        if (!count($tags)) return;
        foreach ($tags as $tag) {
            $model = static::findOne(['object_id'=>$objId,'tag_id'=>$tag]);
            if (!$model) continue;
            $model->delete();
        }
        return;
    }


    public function dataListTableByType($post) {
        //请求参数组装
        $where = ["and"];
        if (!empty($post['tag_id'])) {
            $where[] = ['=','tag_id',$post['tag_id']];
        }
        $query = self::find()->where($where);
        $dataArr = self::table($query,$post);
        return $dataArr;
    }


    public static function artRelieve($object_id,$tag_id) {
        $model = static::find()->where(['object_id'=>$object_id,'tag_id'=>$tag_id])->one();
        if ($model) {
             $model->delete();
        }
        return true;
    }


    public static function getTagInfoByArtId($article_id) {
        $key = "tag_info:article:".$article_id;
        $data = CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            $tag_ids = static::find()->select("tag_id")->where(['object_id' => $article_id])->column();
            if ($tag_ids) {
                foreach ($tag_ids as $tag_id) {
                    $data[] = [
                        'id' => $tag_id,
                        'text' => Tags::getFieldById($tag_id),
                        'tag_url' => CommonUtil::generateUrl($tag_id, Constant::ROUTE_TAG)
                    ];
                }
            }
        }
        return $data;
    }

    public static function getTagStrByArtId($aid) {
            $tag_arr = static::find()->select("tag_id")->where(['object_id'=>$aid])->column();
            $data = implode(',',$tag_arr);
        return $data;
    }
    /**
     * 获取话题下的所有文章
     * @param $tag_id
     * @param $page
     * @param $pageSize
     * @return mixed
     */
    public static function getArticleByTagId($tag_id,$page,$pageSize) {
        $cache_key = "tag:relation:tag_id:".$tag_id.":article:page".$page;
        $data = CommonUtil::getCache(__CLASS__,$cache_key);
        if (!isset($data['total']) || !$data['total']) {
            $data = ['total'=>0,'rows'=>[],'pageSize'=>$pageSize];
            $q = (new Query())->from(self::tableName())
                ->join('left join','zt_article','zt_article.id = zt_tags_relation.object_id')
                ->where(["zt_tags_relation.tag_id"=>$tag_id,"zt_article.status"=>Article::STATUS_PASS])
                ->orderBy("zt_article.release_at desc,object_id DESC");
            $tmpData = self::arrListByPage($q,$page,$pageSize);
            if (count($tmpData['rows'])) {
                $result = [];
                foreach ($tmpData['rows'] as $key=>$val) {
                    $artileModel = Article::findOne(['id'=>$val['object_id'],'status'=>Article::STATUS_PASS]);
                    if (!$artileModel) {
                        unset($tmpData['rows'][$key]);
                        $tmpData['total']--;
                        continue;
                    }
                    $cate_arr = explode(',',$artileModel->cate_id);
                    $result[] = [
                        'id'=>$artileModel->id,
                        'title'=> $artileModel->title,
                        'collect_total' => $artileModel->collect_total?:0,
                        'like_total' => $artileModel->like_total,
                        'comment_total' => $artileModel->comment_total,
                        'summary' => $artileModel->summary,
                        'tags' => self::getTagInfoByArtId($artileModel->id),
                        'link' => CommonUtil::generateUrl($artileModel->id,Constant::ROUTE_ARTICLE),
                        'cate_name' => Category::getFieldById($cate_arr[0]),
                        'cate_url' =>$cate_arr[0]==0?'':CommonUtil::generateUrl($cate_arr[0],Constant::ROUTE_CATEGORY),
                        'cover_image' => isset($artileModel['cover_image'])?$artileModel['cover_image']:"",
                        'created_at' => CommonUtil::formatTime($artileModel->release_at),
                        'date' => date('Y-m-d H:i',$artileModel->release_at)
                    ];
                }
                $data['total'] = $tmpData['total'];
                $data['rows'] = $result;
                if (count($data['rows'])) {
                    CommonUtil::setCache(__CLASS__,$cache_key,$data,86400);
                }
            }
        }
        return $data;
    }

    public static function arrObjectIds($tagIds) {
        return  static::find()->select("DISTINCT(object_id)")
            ->where(["type"=>TagsRelation::TYPE_ARTICLE])
            ->andWhere(["in","tag_id",$tagIds])
            ->column();
    }
    public static function getAllTags(){
         return  Tags::getAllTags();
    }

}
